//LiuZh 2017-07-02
import React, { Component } from 'react';

import {
	View,
	Image,
	Text,
	Dimensions,
	StyleSheet,
	Slider,
	TouchableWithoutFeedback,
	TouchableOpacity,
	FlatList,
	ScrollView
} from 'react-native';

/*

require('ErrorUtils').setGlobalHandler(function (err) {
   console.log('Just ignore:'+error);
});
*/


let winWidth = Dimensions.get('window').width;//屏幕宽度


import Video from 'react-native-video';
import VideoFLItem from '../component/VideoFLItem';

import VideoEmitter from 'shequnsiweiapp/src/events/VideoEmitter.js';


import ToastUtil from 'shequnsiweiapp/src/core/utils/ToastUtil.js';

import Constant from 'shequnsiweiapp/src/core/constant/Constant';
import TabNavView from 'shequnsiweiapp/src/nav/TabNavView.js';


import Http from 'shequnsiweiapp/src/core/utils/Http.js';
import InitDB from 'shequnsiweiapp/src/core/database/InitDB.js';
let { Loading, EasyLoading } = require('react-native-easy-loading');

import Util from '../../../core/utils/util';

let topImg = require('shequnsiweiapp/src/img/video_topImg.png');
let preImg = require('shequnsiweiapp/src/img/video_pre.png');
let playImg = require('shequnsiweiapp/src/img/video_play.png');
let nextImg = require('shequnsiweiapp/src/img/video_next.png');
let zlyImg = require('shequnsiweiapp/src/img/self_zhaoliying.png');
let itemPlayImg = require('shequnsiweiapp/src/img/video_item_playing.png');
let jiantouShangImg = require('shequnsiweiapp/src/img/jiantou_shang.png');
let jiantouXiaImg = require('shequnsiweiapp/src/img/jiantou_xia.png');


let pauseImg = require('shequnsiweiapp/src/img/video_pause.png');







let baseUrl = "";



let list = [];





let voices;

let totalTime = 0;
let currTime = 0;
let currItem = 0;
let preItem = -1;

let sliderValue = 0;
let seconds_ = 0;
let navigation;
let params;
let paused = true;


console.error = (error) => error.apply;

let instance;

export default class VideoScene extends Component {




	constructor(props) {
		super(props);
		voices = InitDB.getVoices();

		this.state = {
			rate: 1,
			//currTime: currTime,
			totalTime: totalTime,
			paused: paused,
			sliderValue: sliderValue,
			seconds_: seconds_,
			price_: 0,

		}



		this.setCurr.bind(this);
		this.pauseOrRun.bind(this);

		navigation = this.props.navigation;
		params = navigation.state.params;

		instance = this;




	}


	componentWillReceiveProps(nextProps) {

		//ToastUtil.show('componentWillReceiveProps');

	}




	componentDidMount() {

		//alert('componentDidMount');



		VideoEmitter.on('VideoOnProgress', (currentTime) => {

			try {




				if (currentTime === this.state.seconds_) {
					instance.next();

				} else {



					//let scale = time / totalTime;
					//console.log(scale * (winWidth - 20));
					//ToastUtil.show(currentTime+",seconds:"+this.state.seconds_);
					this.setState({
						currTime: Util.getTimeBySeconds(currentTime),
						sliderValue: currentTime
					});
			    	Promise.resolve().then(EasyLoading.dismis());

				}

			} catch (e) {
				ToastUtil.show('addListener:' + e);
			}

		})

		VideoEmitter.addListener('VideoOnLoad', (duration) => {
			ToastUtil.show('音频时长:' + duration + "秒");
			instance.setState({ seconds_: duration, totalTime: Util.getTimeBySeconds(duration) });
		})


  

		VideoEmitter.addListener('VideoOnBuffer', (data) => {
				Promise.resolve().then(EasyLoading.dismis());

			/*if (!data.isBuffering) {

				
			}
			*/
		})
 

		
		let courses = InitDB.getCourses();

		if (courses && courses[0]) {
			this.setState({
				price_: courses[0].price_
			})


		}


		// ToastUtil.show(params.ORDER_);
	   // ToastUtil.show('序号:' + params.ORDER_);
		if (params.ORDER_ || params.ORDER_ ===0) {

			

			//VideoEmitter.emit("setPause", true);

			 
			instance.setCurr(params.ORDER_);
		}





	}



	componentWillUnmount() {
		totalTime = this.state.totalTime;
		paused = this.state.paused;
		sliderValue = this.state.sliderValue;
		seconds_ = this.state.seconds_;
		//currTime = this.state.currentTime;

	}

	getCurrItemData() {
		let currentItemData = voices[currItem];
		return currentItemData;
	}


	onStart = () => {

	}


	onError = (e) => {
		ToastUtil.show(e);
	}



	onEnd = () => {
		this.next();
	}



	next = () => {

		this.setCurr(currItem + 1);

	}

	pre = () => {
		this.setCurr(currItem - 1);
	}


	pauseOrRun() {

		//ToastUtil.show('pauseOrRun');

		if (this.state.paused) {
			//this.setCurr(currItem);
		 // Promise.resolve().then(EasyLoading.show('正在加载音频', 1000 * 1000));

			this.setState({
				paused: false
			});

			VideoEmitter.emit("setPause", false);
		} else {
			this.setState({
				paused: true
			});

			VideoEmitter.emit("setPause", true);




		}



	}


	setCurr = (curr, loading = true) => {


	

		if (curr === -1) {
			ToastUtil.show('前面没有更多了');
			return;
		}

		if (curr == voices.length) {
			ToastUtil.show('后面没有更多了');
			return;

		}
		
		
			Promise.resolve().then(EasyLoading.show('音频较大请等待...', 1000 * 1000));
			
	
			preItem = currItem;
		

		currItem = curr;

		//ToastUtil.show('setCurr:' + currItem);


		//VideoEmitter.emit("setPause", true);


		let c = InitDB.getCourseUserCurrentUser() && InitDB.getCourseUserCurrentUser().length > 0
			&& InitDB.getCourseUserCurrentUser()[0].ID_;
		if (voices[currItem].FREE_ === '0' && !c) {
			ToastUtil.show('该音频为vip音频，必须购买专栏才能收听');
			Promise.resolve().then(EasyLoading.dismis());
			return;
		}


		for (let i = 0; i < list.length; i++) {
			try {
				list[i].changeCurrItem(curr);
			} catch (e) {
				// ToastUtil.show('报错了:'+e);
			}
		}

		//	if (voices[curr] && voices[curr].URL_ && voices[curr].URL_ != 'undefined') {
		//alert("seconds:"+voices[curr].SECONDS_);
		this.setState({
			currTime: '00:00',
			sliderValue: 0,
			//seconds_: voices[curr].SECONDS_,
			paused: false,
			//totalTime: voices[curr].TIME_,
		})
		VideoEmitter.emit("setUrlAndTitle", baseUrl + voices[curr].URL_, voices[curr].TITLE1);
		VideoEmitter.emit("setPause", false);
		//ToastUtil.show('setCurr完毕' + voices[curr].URL_);


		/*} else {
			this.setState({
				url: '',
				currTime: '00:00',
				paused: true,
				seconds_: 0,
			})
    }
    */
	}

	renderFLItem = (data) => {
		if (data.item.ID_ == -1) {
			return (
				<View />
			)
		}

		return (
			<VideoFLItem data={data.item}
				onPress={this.setCurr}
				ref={(e) => list.push(e)}
				currId={currItem} />
		)
	}




	pressChangeWindow(showType) {
		this.setState({ showType: showType });
	}








	render() {
		let currentItemData = this.getCurrItemData();
		return (<ScrollView>
			<Loading />
			<View style={{ height: -200 }} />
			<Image style={styles.topImg}
				resizeMode={'contain'}
				source={topImg}>
			</Image>
			<Slider
				ref='slider'
				style={{ backgroundColor: '#FFF' }}
				value={this.state.sliderValue}
				maximumValue={this.state.seconds_}
				step={1}
				minimumTrackTintColor='#FFDB42'
				onValueChange={(value) => {
					//alert('变化了 ');
					this.setState({
						currentTime: value,
					})

				}}
				onSlidingComplete={(value) => {

					try {

						VideoEmitter.emit('VideoSeek', value);


						//TabNavView.getVideo().seek(value);

						// ToastUtil.show('listenerCount:'+VideoEmitter.listenerCount('VideoOnProgress')+",seconds:"+this.state.seconds_);
						//VideoEmitter.removeAllListeners("VideoOnProgress");
						//  params.Video.seek(value);
						//  params.seek(value);
						//  alert(params.video.seek);
						//  params.video.seek(value);

						//this.addVideoProgress();

					} catch (e) {
						ToastUtil.show('报错:' + e);
					}
					/*alert('onSlidingComplete');
					if (this.state.url) {
						
					}
					*/
					//	this.refs.video.seek(value);

				}} />
			<View style={styles.controlBox}>
				<Text style={styles.progressTxt}>{this.state.currTime}</Text>
				<TouchableWithoutFeedback
					onPress={this.pre}>
					<Image style={styles.pnImg}
						source={preImg} />
				</TouchableWithoutFeedback>
				<TouchableWithoutFeedback
					onPress={this.pauseOrRun.bind(this)}>
					<Image style={styles.playImg}
						source={this.state.paused ? playImg : pauseImg} />
				</TouchableWithoutFeedback>
				<TouchableWithoutFeedback
					onPress={this.next}>
					<Image style={styles.pnImg}
						source={nextImg} />
				</TouchableWithoutFeedback>
				<Text style={[styles.progressTxt, { textAlign: 'right', paddingRight: 20, paddingLeft: 0 }]}>{this.state.totalTime}</Text>
			</View>
			<View style={styles.lmBox}>
				<Image style={{ height: 50, width: 50, margin: 10 }}
					source={zlyImg} />
				<View >
					<Text style={{ color: '#000', fontSize: 16 }}>付岩说</Text>
				</View>
				<View style={{ flex: 1 }} />


				{
					this.state.price_ === 0 ?
						<View />
						:

						<TouchableOpacity
							activeOpacity={0.7}
							style={styles.buyBtn} onPress={Http.goumai}>
							<Text style={{ color: '#FFF', fontSize: 16 }}>购买</Text>
						</TouchableOpacity>

				}


			</View>
			<FlatList
				data={voices}
				renderItem={this.renderFLItem} />
		</ScrollView>
		)
	};


}

const styles = StyleSheet.create({


	topImg: {
		height: 417 / 750 * winWidth,
		width: winWidth,
	},
	slider: {
		width: winWidth,
		position: 'absolute',
		height: 20,
		top: 190,
		zIndex: 111,
	},
	touchSlider: {
		height: 20,
		width: 20,
		backgroundColor: '#FFF',
		borderRadius: 10,
		zIndex: 113,
		borderColor: '#DDD',
		borderWidth: 0.5,
	},
	sliderLine: {
		width: winWidth,
		height: 4,
		backgroundColor: '#DDD',
		position: 'absolute',
		top: 8,
		left: 0,
		zIndex: 112,
	},
	controlBox: {
		flexDirection: 'row',
		height: 80,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
		backgroundColor: '#FFF'
	},
	progressTxt: {
		flex: 1,
		fontSize: 10,
		color: '#AAA',
		alignSelf: 'flex-start',
		paddingTop: 6,
		paddingLeft: 20,
	},
	pnImg: {
		width: 18,
		height: 18
	},
	playImg: {
		height: 50,
		width: 50,
		marginLeft: 34,
		marginRight: 34,
	},
	lmBox: {
		height: 70,
		padding: 8,
		backgroundColor: '#FFF',
		justifyContent: 'center',
		alignItems: 'center',
		flexDirection: 'row',
		marginBottom: 10,
	},
	buyBtn: {
		marginRight: 10,
		backgroundColor: '#EE0',
		paddingLeft: 20,
		paddingRight: 20,
		paddingTop: 8,
		paddingBottom: 8,
		borderRadius: 5,
	},
	flItem: {
		height: 50,
		backgroundColor: '#FFF',
		flexDirection: 'row',
		justifyContent: 'flex-start',
		alignItems: 'center',
		paddingLeft: 20,
		marginBottom: 1
	}


});